from django import forms
from django.forms import  widgets,ValidationError
from .models import User
from captcha.fields import CaptchaField

class UserLoginForm(forms.Form):
    """
    用户登录
    """
    msg = {"required":"该字段不能为空"}
    username = forms.CharField(max_length=10,label="用户名",error_messages=msg,
                               widget=widgets.TextInput(attrs={"class":"form-control"}))
    password = forms.CharField(max_length=32,label="密码",error_messages=msg,
                               widget=widgets.PasswordInput(attrs={"class":"form-control"}))
    captcha = CaptchaField(label='验证码')

    # def clean_username(self):
    #     user = self.cleaned_data.get("username")
    #     user_obj = User.objects.filter(username=user)
    #     if not user_obj:
    #         return user_obj
    #     else:
    #         raise ValidationError("用户名不能为空!")




class UserRegisterModelForm(forms.ModelForm):
    username = forms.CharField(max_length=32,min_length=2,label="用户名",
                               widget=widgets.TextInput(attrs={"class":"form-control"}))
    email = forms.CharField(max_length=32,label="邮箱",
                             widget=widgets.EmailInput(attrs={"class":"form-control"}))
    password = forms.CharField(max_length=32,min_length=3,label="密码",
                               widget=widgets.PasswordInput(attrs={"class":"form-control"}))
    password2 = forms.CharField(max_length=32,min_length=3,label="确认密码",
                                widget=widgets.PasswordInput(attrs={"class": "form-control"}))
    captcha = CaptchaField(label='验证码')

    class Meta:
        model = User    # 对User表进行校验
        fields = ['username','email','password']    # 需要校验的字段
        labels = {"username":"用户名","password":"密码",'email':"邮箱"}



        def __init__(self,*args,**kwargs):
            super().__init__(*args,**kwargs)
            for field in self.fields.values():
                field.error_messages = {"required": "该字段不能为空"}
                field.widget.attrs.update({"class":"form-control"})


    def clean_username(self):
        user = self.cleaned_data.get("username")
        ret = User.objects.filter(username=user)
        if not ret:
            return user
        else:
            raise ValidationError("用户名已存在!")    # 抛出异常

    def clean_password(self):
        pwd = self.cleaned_data.get("password")
        if pwd.isdigit():
            raise ValidationError("密码不能是纯数字!")
        elif len(pwd) <= 3:
            raise ValidationError("密码不能少于3位")
        else:
            return pwd

    # 对两次密码进行校验
    def clean(self):
        pwd = self.cleaned_data.get("password")
        r_pwd = self.cleaned_data.get("password2")
        print(pwd,r_pwd)
        if pwd and r_pwd and pwd != r_pwd:
            raise ValidationError("两次密码不一致!")
        else:
            return self.cleaned_data    # 密码和确认密码相同直接通过


class ProfileForm(forms.Form):
    class Meta:
        # 关联的数据库模型，这里是用户模型
        model = User
        # 前端显示、可以修改的字段（admin中）
        fields = ['nickname','link','avatar']











